<?php
/**
 * Created by PhpStorm .
 * User: {Administrator}
 * Date: {2022/7/6 16:37}
 * Author: '树叶'
 * Email: 'ayunu@qq.com'
 * Motto Info: '理想如果不向现实做一点点屈服，那么理想也将归于尘土。'
 */

namespace app\api\model;
use think\Db;
use think\Model;
use app\api\model\UserHistory as UserHistoryModel;
use app\api\model\GoodsItem as GoodsItemModel;
use app\api\model\Config as ConfigModel;
use app\api\model\User as UserModel;

class GoodsShare extends Model
{
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = '';
    protected $resultSetType = 'collection';
    // 追加属性
    protected $append = [

    ];

    /**
     * 添加积分
     */
    public static function addShare($share_id, $uid, $gid, $integral, $order_id)
    {
        if (empty($share_id) || empty($uid) || empty($gid) || empty($integral) || empty($order_id))
        {
            return false;
        }


        $where = [];
        $where['share_id'] = ['eq',$share_id];
        $where['uid'] = ['eq',$uid];
        $where['gid'] = ['eq',$gid];
        $response = Db::name('goods_share')->where($where)->find();

        if ($response)
        {
            return true;
        }

        $data = [
            'share_id' => $share_id,
            'uid' => $uid,
            'gid' => $gid,
            'integral' => $share_id,
            'orderid' => $order_id,
            'create_time' => time()
        ];

        $res = Db::name('goods_share')->insertGetId($data);

        return $res;
    }

    /**
     * 发放积分
     */
    public static function upShare($id)
    {
        if (empty($id)) return false;
        $share = Db::name('goods_share')->where('orderid',$id)->find();
        if (empty($share) || $share['issue'] == 1) return false;

        Db::startTrans();
        try {
            $res = Db::name('goods_share')->where('orderid', $id)->update(['issue' => 1, 'update_time' => time()]);
            if (!$res) return false;
            Db::name('user')->where('id',$share['share_id'])->setInc('score',$share['integral']);
            Db::name('user')->where('id',$share['share_id'])->setInc('scoresum',$share['integral']);
            Db::name('user')->where('id',$share['uid'])->setInc('score', $share['integral']);
            Db::name('user')->where('id',$share['uid'])->setInc('scoresum', $share['integral']);
            $genre = '分享商品';
            $time = time();
            $data = [
                ['uid' => $share['share_id'], 'integral' => $share['integral'], 'type' => 3, 'genre' => $genre, 'create_time' => $time],
                ['uid' => $share['uid'], 'integral' => $share['integral'], 'type' => 3, 'genre' => $genre, 'create_time' => $time],
            ];
            Db::name('integral')->insertAll($data);
            Db::commit();
            return true;
        }catch(\Exception $e){
            var_dump($e->getMessage());
            Db::rollback();
            return false;
        }


    }
}